package fun.ipconfig.shopping.service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import fun.ipconfig.shopping.configure.exception.ResultException;
import fun.ipconfig.shopping.dao.UserDetailsDao;
import fun.ipconfig.shopping.entity.Result;
import fun.ipconfig.shopping.entity.UserEntity;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * @author gtl
 */
@Service
public class UserService {

    private final UserDetailsDao userDetailsDao;

    private final PasswordEncoder passwordEncoder;

    WebApplicationContext applicationContext;
    public UserService(UserDetailsDao userDetailsDao,PasswordEncoder passwordEncoder, WebApplicationContext applicationContext){
        this.userDetailsDao = userDetailsDao;
        this.passwordEncoder = passwordEncoder;
        this.applicationContext = applicationContext;
    }
    
    /**
     * 添加用户
     * @param users
     * @return
     */
    @PreAuthorize("hasAnyRole('user_add')")
    public Result addUser(List<UserEntity> users){
        // 默认过期事件
        final Date expire = new Date(System.currentTimeMillis() + 90L * 24 * 60 * 60 * 1000 );
        // 密码加密
        users.forEach(u->{
            u.setAccountExpired(u.getAccountExpired()== null ? expire : u.getAccountExpired());
            u.setCredentialsExpired(u.getCredentialsExpired() == null ?  expire : u.getCredentialsExpired() );
            u.setName(u.getName() == null ? "" : u.getName());
            if(u.getUser() == null) {
                throw new ResultException().setMsg("不能为空").setStatus(500);
            }
            if(u.getPasswd() == null) {
                throw new ResultException().setMsg("密码不能为空").setStatus(500);
            }
            u.setPasswd(passwordEncoder.encode(u.getPassword()));
        });
        userDetailsDao.addUsers(users);
        return new Result().setMsg("添加成功").setStatus(200);
    }

    /**
     * 获取所有定义的接口
     * @return
     */
    public List<String> getAllUrl(){
        String UrlPackage = "fun.ipconfig";
        RequestMappingHandlerMapping mapper = applicationContext.getBean(RequestMappingHandlerMapping.class);
        List<String> list = new LinkedList<String>();
        mapper.getHandlerMethods().forEach((f,v)->{
            if(v.getBeanType().getName().startsWith(UrlPackage)){
                assert f.getPathPatternsCondition() != null;
                list.addAll(f.getDirectPaths());
            }
        });
        return list;
    }
    
    /**
     * 获取当前的用户
     * @return
     */
    public UserEntity getCurrentLoginUser(){
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!(user instanceof UserEntity)){
            throw new ResultException().setMsg("用户未登录").setStatus(403);
        }
        return (UserEntity)user;
    }
}
